<template>
  <div class="subcontract-registration-manage">
    <div class="model-title-css">
      <div>安全整改</div>
      <el-button class="liuchengbtn" style="margin-left:10px;" type="text" @click="processDialog=true">
        <i class="iconfont "></i> 流程示意图
      </el-button>
    </div>
    <el-dialog width="1200px" class="dialog" title="流程示意图" :visible.sync="processDialog" v-dialog-drag :modal-append-to-body="false" :close-on-click-modal="false" append-to-body>
      <el-image style="display:block;height:600px" class="g-dialog-img" :src="require('@/assets/images/liuchengtu/safecheck.png')" alt="" :preview-src-list="[require('@/assets/images/liuchengtu/safecheck.png')]" />
    </el-dialog>

    <div class="background_wrap public-flex-row">
      <div class="left-box WholeScroll">
        <el-tree class="Public-Tree-Class" :data="leftList" :props="defaultProps" ref='treeData' node-key="id" :highlight-current='true' :default-expanded-keys="defaultTreeKey" @node-click="handleNodeClick"></el-tree>
      </div>
      <div class="right-box">
        <div class="operate_wrap flex">
          <div class="flex-center">
            <el-button type="primary" size="small" class="add buildButtonStyle" v-permission="permission.add" round @click="showDialog('build', '新增')"><i class="iconfont icon-icon_add"></i> 新增
            </el-button>
          </div>
          <div class="flex-right-action-group">
            <el-input class="input" size="small" style="width: 160px" v-model="search.serialNumber" @keyup.enter.native="keydown()" placeholder="请输入编号" clearable @clear="getList(true)"></el-input>
            <!--   <el-select
               class="select"
               size="small"
               v-model="search.sectionId"
               v-on:change="getLeftTrees()"
               value-key="id"
               placeholder="选择标段"
             >
               <el-option
                 v-for="item in sectionTree"
                 :key="item.id"
                 :label="item.name"
                 :value="item.id"
               >
               </el-option>
             </el-select>

        <el-select
             class="select"
             size="small"
             @change="getList(true)"
             v-model="search.inspectionLevel"
             placeholder="选择检查级别"
             clearable
           >
             <el-option
               v-for="item in inspectionLevelList"
               :key="item.code"
               :label="item.name"
               :value="item.code"
             >
             </el-option>
           </el-select>-->
            <el-date-picker v-model="search.inspectionTime" value-format="yyyy-MM-dd" type="daterange" style="width:300px;margin-left: 15px;" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" @change="getList(true)">
            </el-date-picker>
            <el-button class="search" size="small" @click="getList(true)">
              <i class="iconfont icon-sousuo"></i>&nbsp;搜索
            </el-button>
          </div>
        </div>
        <div class="list_wrap">
          <el-table :border="true" :row-class-name="tableRowStyleName" :cell-class-name="tableCellStyleName" :header-cell-class-name="tableHeaderCellStyleName" :stripe="true" ref="multipleTable" :data="list" tooltip-effect="dark" @cell-click="cellClick" style="width: 100%; font-family: PingFangSC-Regular; font-size: 14px">
            <el-table-column show-overflow-tooltip prop="xh" align="center" label="序号" width="60">
              <template slot-scope="scope">
                {{ scope.$index + search.pageNo * search.pageSize + 1 }}
              </template>
            </el-table-column>
            <el-table-column show-overflow-tooltip label="编号" prop="serialNumber" width="140">
            </el-table-column>
            <el-table-column show-overflow-tooltip prop="sectionName" label="标段" width="230">
            </el-table-column>
            <el-table-column show-overflow-tooltip label="检查日期" prop="inspectionTime" width="160">
            </el-table-column>

            <el-table-column show-overflow-tooltip label="检查人员" prop="inspector" width="150">
            </el-table-column>
            <!--    <el-table-column
              show-overflow-tooltip
              label="级别"
              width="80"
            >
              <template slot-scope="scope">
                <div>
                  {{scope.row.inspectionLevel | optionFilterByRow({ options: inspectionLevelList, labelKey: 'name', valueKey: 'code' })}}
                </div>
              </template>
            </el-table-column>-->
            <el-table-column show-overflow-tooltip label="隐患数量" width="110">
              <template slot-scope="scope">
                <div style="text-align: right;">{{scope.row.hiddenDangersNumber}}</div>
              </template>
            </el-table-column>

            <el-table-column show-overflow-tooltip label="整改期限" width="150" prop="rectificationDeadline">
            </el-table-column>

            <el-table-column show-overflow-tooltip label="审批状态" width="170">
              <template slot-scope="scope">
                <div v-if="scope.row.nodeName" style="text-align: left;" v-html="scope.row.nodeName"></div>
                <div v-else style="text-align: left;">待上报</div>
              </template>
            </el-table-column>
            <el-table-column show-overflow-tooltip label="操作" width="300" fixed="right">
              <template slot-scope="scope">
                <work-flow-btn v-if="scope.row.needRectification === '1'" :row="scope.row" :type="2" @edit="edit" @del="del" @approve="approve" @detail="detail" />
                <div v-if="scope.row.needRectification === '2'">
                  <el-button size="mini" v-permission="permission.show" class="menu_icon iconfont icon-icon_look action_color1" @click="showDialog('check','查看',scope.row.id)">&nbsp;查看</el-button>
                  <!-- <el-button size="mini" class="menu_icon iconfont icon-xiugai-copy action_color1" v-permission="permission.edit" @click="showDialog('edit','编辑',scope.row.id)">&nbsp;修改</el-button>
                  <el-button size="mini" class="menu_icon iconfont icon-shanchu action_color2" v-permission="permission.del" @click="showDialog('delete','删除',scope.row.id)">&nbsp;删除</el-button> -->
                </div>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination style="float: right; margin-top: 15px" layout="prev, pager, next" :page-size="search.pageSize" :total="search.total" :current-page="search.pageNo + 1" :prev-text="tablePaginationPrev" :next-text="tablePaginationNext" @current-change="paginationChange">
          </el-pagination>
        </div>
      </div>
    </div>

    <Detail :postDetail="postDetailData" @reloadList="getList(true)"></Detail>
  </div>
</template>

<script>
import {
  tableRowStyleGol,
  tableCellStyleGol,
  tableHeaderCellStyleGol,
  doCreateObject
} from '@/utils/publicFun'
import safetyRectification, { listPage } from '@/api/buss/safetyRectification'
import msgUtil from '@/utils/msgUtil'
import projectSectionInfo from '@/api/buss/common'
import crudDict from "@/api/system/dict";
import WorkFlowBtn from '@/components/WorkFlow/table'
import publicSearchData from '@/mixins/publicSearchData'
export default {
  name: `demo`,
  mixins: [publicSearchData],
  components: {
    WorkFlowBtn,
    Detail: require(`./safetyRectification-detail`).default,
  },
  data() {
    return {
      processDialog: false,
      leftList: [],
      sectionTree: [],
      defaultTreeKey: [],
      defaultProps: {
        children: 'children',
        label: 'name',
      },
      chooseTreeData: {},
      permission: {
        add: ['100', '1009155:add'],
        show: ['100', '1009155:show'],
        edit: ['100', '1009155:edit'],
        del: ['100', '1009155:del'],
      },
      tableRowStyleName: tableRowStyleGol,
      tableCellStyleName: tableCellStyleGol,
      tableHeaderCellStyleName: tableHeaderCellStyleGol,
      tablePaginationPrev: '上一页',
      tablePaginationNext: '下一页',
      hasAdd: false, //是否有新增权限
      loading: false,
      //  当前查看的文件列表
      nowFileList: [],
      showFileDialog: false,
      // list: [{}, {}, {}, {}],
      list: [],
      title: '人员',
      addSectionId: '',
      projectTypeArr: [],
      projectStatusArr: [],
      inspectionLevelList: [],
      // 搜索参数
      search: {
        //pageIndex: 0,
        pageNo: 0,
        pageSize: 10,
        //pageSum: 0,
        total: 0,
        sectionId: '',
        projectId: '',
        sortType: '',
        noticeNum: '',
        serialNumber: '',
        completeCondition: '',
        inspectionLevel: '',
        inspectionTime: '',
      },

      // 向详情子组件的传值
      postDetailData: {
        show: false,
        type: 'build',
        typeName: '新增',
      },
      postDetailData2: {
        show: false,
        type: 'import',
        typeNmae: '导入'
      },
      // 向详情子组件的传值
      treeEditDialogData: {
        show: false,
        nowTreeData: []
      },
    }
  },
  mounted() {
    this.initData()
    this.getInspectionLevel()
  },
  methods: {
    keydown() {
      if (event.keyCode == 13) {
        this.getList(true)
      }
    },
    //  下载模板
    downfile() {
      safetyRectification.downfile(this.search).then(res => {
        doCreateObject(res, '农民工工资登记模板.xlsx')
      }).catch(e => {
        console.log(e);
        this.$messageError("请求excel模板失败")
      })
    },
    getInspectionLevel() {
      crudDict.getByCode('inspectionLevel').then(res => {
        if (res.code == 200) {
          this.inspectionLevelList = res.data
        }
      })
    },
    //导出
    exportExcel() {
      //条件自己写咩

      let params = {
        sectionId: this.search.sectionId,
        date: this.search.date,
        farmerName: this.search.farmerName,
      }
      safetyRectification.exportExcel(params).then(res => {
        doCreateObject(res, '导出.xls')
      })
    },
    //  导入excel
    importExcel() {
      this.postDetailData2 = {
        show: true,
        type: 'import',
        typeName: '导入'
      }
      //触发 文件选择的click事件
      // $("#excel-import-button").trigger("click");
    },
    approve(obj) {
      this.postDetailData = {
        show: true,
        type: 'approve',
        typeName: '审核',
        detailId: obj.id,
        search: this.search
      }
    },
    edit(obj) {
      this.postDetailData = {
        show: true,
        type: 'edit',
        typeName: '编辑',
        detailId: obj.id,
        search: this.search
      }
    },
    detail(obj) {
      this.postDetailData = {
        show: true,
        type: 'check',
        typeName: '查看',
        detailId: obj.id,
        search: this.search
      }
    },
    del(obj) {
      if (obj.id === '') {
        msgUtil.error2('请先选择要删除的记录！')
        return
      }
      msgUtil.confirm('确认删除该条数据?').then(res => {
        let idlist = []
        idlist.push(obj.id)
        let param = {
          ids: idlist
        }
        safetyRectification.del(param).then(res => {
          if (res.code === 200) {
            msgUtil.success2('删除成功!')
            this.getList()
          } else {
            msgUtil.error2(res.data.message)
          }
        })
      })
    },



    initData() {
      projectSectionInfo.getLeftProjectTree().then(res => {
        if (res.code === 200) {
          this.$set(this, 'leftList', res.data)
          this.$nextTick(() => {
            if (this.$headerSearch) {
              if (this.changeHeaderProject) {
                this.$refs['treeData'].setCurrentKey(this.changeHeaderProject);
                if (this.defaultTreeKey) {
                  this.defaultTreeKey.push(this.changeHeaderProject)
                }
                this.handleNodeClick({
                  id: this.changeHeaderProject,
                  tpye: 'projectId'
                })
              } else {
                this.defaultTreeKey.push(this.leftList[0].id)
                this.$refs['treeData'].setCurrentKey(this.leftList[0].id);
                if (this.defaultTreeKey) {
                  this.defaultTreeKey.push(this.leftList[0].id)
                }
                this.handleNodeClick(this.leftList[0])
              }
            } else {
              this.defaultTreeKey.push(this.leftList[0].id)
              this.$refs['treeData'].setCurrentKey(this.leftList[0].id);
              if (this.defaultTreeKey) {
                this.defaultTreeKey.push(this.leftList[0].id)
              }
              this.handleNodeClick(this.leftList[0])
            }
          })
        } else {
          this.$messageError(res.data.message)
        }
      }).catch(() => {
        this.$messageError('获取项目标段树失败')
      })
    },


    // 事件处理的api请求
    sealDealHttp(url, query, param, callback) {
      this.$httpPost(url + query, param)
        .then((res) => {
          if (res.status === 1) {
            if (callback) callback(res)
            // 重新获取数据
            setTimeout(() => {
              this.getList(true)
            }, 1000)
          } else {
            this.$messageError(res.message)
          }
        })
        .catch((res) => {
          console.log('请求出现错误', res)
          console.log(res)
        })
    },
    handleNodeClick(data) {
      this.search.projectId = '';
      this.search.sectionId = '';

      console.log(data);
      if (data.type == 'projectId') {
        this.search.projectId = data.id;
        this.search.projectName = data.name;
      }
      if (data.type == 'sectionId') {
        this.search.sectionId = data.id;
        this.search.sectionName = data.name;
        this.search.projectId = this.getProjectIdBySectionId(this.search.sectionId).id
        this.search.projectName = this.getProjectIdBySectionId(this.search.sectionId).name
        this.addSectionId = data.id;
      }
      this.getList(true)
    },
    getProjectIdBySectionId(sectionId) {
      for (let i in this.leftList) {
        if (this.leftList[i].hasOwnProperty('children') && this.leftList[i].children.length > 0) {
          for (let j in this.leftList[i].children) {
            if (this.leftList[i].children[j].id == sectionId) {
              return this.leftList[i]
            }
          }
        }
      }
    },
    // 格式化表单数据
    formatter(row, column) {
      let array = column.property.split('.')
      let result
      array.forEach((item, i) => {
        result = result === undefined ? row[item] : result[item]
      })
      if (result === '' || result === undefined) {
        return '--'
      } else {
        return result
      }
    },
    // 点击单元格
    cellClick(row, column, cell, event) {
      if (column.property === 'protocolNum') {
        this.detail(row)
      }
    },
    // 获取列表 api
    getList(reload) {
      if (reload) {
        this.search.pageNo = 0
      }
      this.list = []
      let param = {
        pageNo: this.search.pageNo,
        pageSize: this.search.pageSize,
        projectId: this.search.projectId,
        sectionId: this.search.sectionId,
        date: this.search.date,
        farmerName: this.search.farmerName
      }

      if (this.search.inspectionTime) {
        this.search.startDate = this.search.inspectionTime[0] + ' 00:00:00'
        this.search.endDate = this.search.inspectionTime[1] + ' 23:59:59'
      } else {
        this.search.startDate = ''
        this.search.endDate = ''
      }
      safetyRectification.listPage(this.search).then(res => {
        if (res.code == 200) {
          this.list = res.data.content
          this.search.total = res.data.totalElements
        } else {
          msgUtil.error2(res.data.message)
        }
      })
    },

    // 切换列表
    paginationChange(index) {
      this.search.pageNo = index - 1
      this.getList()
    },
    /*  操作 */
    showDialog(type, typeName, detailId) {
      if (!this.search.sectionId) {
        this.$messageWarning("请先选择标段")
        return;
      }
      console.log(this.search)
      switch (type) {
        case 'build':
          this.postDetailData = {
            show: true,
            type: type,
            typeName: typeName,
            detailId: '',
            search: this.search
          }
          break
        case 'edit':
          this.postDetailData = {
            show: true,
            type: type,
            typeName: typeName,
            detailId: detailId,
            search: this.search,
            chooseTreeData: this.chooseTreeData,
          }
          break
        case 'check':
          this.postDetailData = {
            show: true,
            type: type,
            typeName: typeName,
            detailId: detailId,
            search: this.search,
            chooseTreeData: this.chooseTreeData
          }
          break
        case 'delete':
          if (detailId === '') {
            msgUtil.error2('请先选择要删除的记录！')
            return
          }
          msgUtil.confirm('确认删除该条数据?').then(res => {
            let idlist = []
            idlist.push(detailId)
            let param = {
              ids: idlist
            }
            safetyRectification.del(param).then(res => {
              if (res.code === 200) {
                msgUtil.success2('删除成功!')
                this.getList()
              } else {
                msgUtil.error2(res.data.message)
              }
            })
          })
          break
      }
    },




  },
}
</script>

<style scoped lang="scss">
.model-title-css {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: flex-start;
}
.list_wrap {
  margin-top: 20px;
}
.left-box {
  min-width: 220px !important;
  max-width: 350px !important;
  max-height: calc(100vh - 200px);
  border-right: 1px #e2e8ec solid;
  overflow: auto;
  p {
    cursor: pointer;
    font-size: 14px;
  }
}
.right-box {
  width: calc(100% - 220px);
  padding: 0 0 0 15px;
  flex-grow: 1;
}
</style>
